import mongoose, { Document, Schema } from 'mongoose'

export interface IReward extends Document {
  userId: mongoose.Types.ObjectId
  roomId?: mongoose.Types.ObjectId
  type: 'gift' | 'popularity'
  period: 'daily' | 'weekly' | 'monthly'
  rank: number
  amount: number // 奖励金额
  status: 'pending' | 'paid' | 'failed'
  rankingHistoryId: mongoose.Types.ObjectId
  paidAt?: Date
  createdAt: Date
}

const RewardSchema = new Schema({
  userId: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true,
  },
  roomId: {
    type: Schema.Types.ObjectId,
    ref: 'Room',
  },
  type: {
    type: String,
    enum: ['gift', 'popularity'],
    required: true,
  },
  period: {
    type: String,
    enum: ['daily', 'weekly', 'monthly'],
    required: true,
  },
  rank: {
    type: Number,
    required: true,
  },
  amount: {
    type: Number,
    required: true,
    min: 0,
  },
  status: {
    type: String,
    enum: ['pending', 'paid', 'failed'],
    default: 'pending',
  },
  rankingHistoryId: {
    type: Schema.Types.ObjectId,
    ref: 'RankingHistory',
    required: true,
  },
  paidAt: Date,
  createdAt: {
    type: Date,
    default: Date.now,
  },
})

// 创建索引
RewardSchema.index({ userId: 1, type: 1, period: 1 })
RewardSchema.index({ status: 1, createdAt: 1 })
RewardSchema.index({ rankingHistoryId: 1 })

export const Reward = mongoose.model<IReward>('Reward', RewardSchema)
